<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import { fetchBarChartViewData } from '@/api/view'

const animationDuration = 6000

const defaultViewdata =
  {
    pass: [790, 52, 200, 334, 390, 330],
    fail: [80, 52, 200, 334, 390, 330],
    unaudited: [30, 52, 200, 334, 390, 220]
  }

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null,
      viewdata: Object.assign({}, defaultViewdata),
      months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 获取数据
      this.fetchViewData()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    fetchViewData() {
      fetchBarChartViewData().then(response => {
        this.viewdata = Object.assign({}, response.data)
        // 初始化柱状图
        this.initChart()
      }).catch(err => {
        console.log(err)
      })
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 10,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [{
          type: 'category',
          data: this.getMonth(),
          axisTick: {
            alignWithLabel: true
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: [{
          name: '以通过',
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: this.viewdata.pass,
          animationDuration
        }, {
          name: '未通过',
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: this.viewdata.fail,
          animationDuration
        }, {
          name: '未审核',
          type: 'bar',
          stack: 'vistors',
          barWidth: '60%',
          data: this.viewdata.unaudited,
          animationDuration
        }]
      })
    },
    getMonth() {
      const date = new Date()
      const currentMonth = date.getMonth() + 1
      let result = []
      for (let i = currentMonth - 5; i <= currentMonth; i++) {
        result.push(this.months[i - 1 >= 0 ? i - 1 : 12 + (i - 1)])
      }
      console.log(result)
      return result
    }
  }
}
</script>
